const express = require('express');
const fs = require('fs-extra');
const path = require('path');
const { v4: uuidv4 } = require('uuid');
const api = require('./api');

const router = express.Router();
const DATA_PATH = path.join(__dirname, '../data/routes.json');

// 工具函数：读取所有路由
function getAllRoutes() {
  return fs.readJsonSync(DATA_PATH, { throws: false }) || [];
}
// 工具函数：写入所有路由
function saveAllRoutes(routes) {
  fs.writeJsonSync(DATA_PATH, routes, { spaces: 2 });
}

// 路由列表页（分页+搜索）
router.get('/', (req, res) => {
  let { page = 1, pageSize = 10, q = '' } = req.query;
  page = parseInt(page);
  pageSize = parseInt(pageSize);
  let routes = getAllRoutes();
  if (q) {
    routes = routes.filter(r => r.name.includes(q) || r.path.includes(q));
  }
  const total = routes.length;
  const list = routes.slice((page-1)*pageSize, page*pageSize);
  res.render('routes_list', { list, total, page, pageSize, q, title: '路由管理' });
});

// 新建路由页
router.get('/new', (req, res) => {
  res.render('routes_edit', { route: null, title: '新建路由' });
});

// 编辑路由页
router.get('/edit/:id', (req, res) => {
  const routes = getAllRoutes();
  const route = routes.find(r => r.id === req.params.id);
  if (!route) return res.status(404).send('未找到路由');
  res.render('routes_edit', { route, title: '编辑路由' });
});

// 新建/编辑提交
router.post('/save', (req, res) => {
  let routes = getAllRoutes();
  const { id, name, method, path: routePath, delay, body, responseScript } = req.body;
  // 唯一性校验
  if (routes.some(r => r.method === method && r.path === routePath && r.id !== id)) {
    return res.send('<script>alert("相同的HTTP方法+路径已存在");history.back();</script>');
  }
  if (id) {
    // 编辑
    routes = routes.map(r => r.id === id ? { ...r, name, method, path: routePath, delay, body, responseScript } : r);
  } else {
    // 新建
    routes.push({ id: uuidv4(), name, method, path: routePath, delay, body, responseScript });
  }
  saveAllRoutes(routes);
  api.reloadMockRoutes && api.reloadMockRoutes();
  res.redirect('/routes');
});

// 删除
router.post('/delete/:id', (req, res) => {
  let routes = getAllRoutes();
  routes = routes.filter(r => r.id !== req.params.id);
  saveAllRoutes(routes);
  api.reloadMockRoutes && api.reloadMockRoutes();
  res.redirect('/routes');
});

module.exports = router; 